/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package vescapecloud.network;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.openstack4j.api.exceptions.AuthenticationException;
import vescapecloud.openstack.Instance;

/**
 * Thread to handle the connection with a client ( Answer and instance creation
 * )
 *
 * @author JulieDu
 */
public class TCPHandleClient implements Runnable {

    private Socket socketServer;

    // input from client
    private String input;

    private Instance instanceClient;

    public TCPHandleClient(Socket server) {
        this.socketServer = server;
    }

    /**
     * Start and Handle single connection for a client
     */
    public void run() {

        BufferedReader inFromClient = null;
        DataOutputStream outToClient = null;
        instanceClient = new Instance();
        // Answer construction
        JSONObject response = new JSONObject();
        try {
            response.put("ip_address", "192.168.0.101");
            response.put("token", "tokenTest");
        } catch (JSONException ex) {
            Logger.getLogger(TCPServer.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            // Get input stream 
            inFromClient = new BufferedReader(
                    new InputStreamReader(
                            socketServer.getInputStream()));

            // Get output stream 
            outToClient = new DataOutputStream(
                    socketServer.getOutputStream());

            // Read input from client
            input = inFromClient.readLine();
            System.out.println("[TCPHandle      ]     Thread client createdReceived: " + input);

            // TODO : check if it's null
            JSONObject json = decode(input);
            System.out.println("[TCPHandle      ]     JSON object decoded");

            // creation of object
            createInstance(json);
            System.out.println("[TCPHandle      ]     Instance Object created");

            // Answer
            System.out.println("[TCPHandle      ]     Answer to client");

            System.out.println("[TCPHandle      ]     Authentification...");
            instanceClient.authentification();

            // boot the instance
            instanceClient.bootServer();
            System.out.println("[TCPHandle      ]     Instance booted");

            Thread.sleep(15000);
            outToClient.writeBytes(response.toString());


        } catch (IOException ex) {
            // Error with stream and socket opening
            Logger.getLogger(TCPHandleClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            // Error during the boot
            Logger.getLogger(TCPHandleClient.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                // close buffer and socket
                inFromClient.close();
                outToClient.close();
                socketServer.close();
            } catch (IOException ex) {
                Logger.getLogger(TCPHandleClient.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * Transform a string into a JSON object and check if the JSON is correctly
     * contructed
     *
     * @param sentence
     * @return JSONObject or null
     */
    private static JSONObject decode(String sentence) {
        // JSON decode and answer to client
        JSONObject jsonObject = null;
        try {

            // TODO : check the validity of the parameters JSON
            jsonObject = new JSONObject(sentence);

        } catch (JSONException ex) {
            Logger.getLogger(TCPServer.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
        return jsonObject;

    }

    /**
     *
     * @param json
     * @return
     */
    private void createInstance(JSONObject json) {

        /* Message received: {"account_type":"123","user_id":"example1@vescape.com",
         "user_pwd":"12345","user_ip":"192.32.15.2","user_API_level":"14",
         "user_opengl_version":"3","user_resolution_width":"320",
         "user_resolution_height":"420","user_gameselected":"greedyRabbit",
         "status":200,"status_message":"parameters ok"}Host: www.example.com */
        try {

           // i.setAccount_type(json.getString("user_resolution_height"));
            //i.setUser_gameselected(json.getString("user_gameselected"));
            // i.setUser_id(json.getString("user_id"));
            instanceClient.setUser_ip(json.getString("user_ip"));
        } catch (JSONException ex) {
            Logger.getLogger(TCPHandleClient.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}
